package com.wlr.blog.web.common.config;

import cn.hutool.log.Log;
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * @author lrwang
 * @version 1.0
 * @date 2022/12/12 10:37
 */
@Configuration
public class RedissonConfig {
    @Value(value = "${spring.redis.host}")
    private String host;
    @Value(value = "${spring.redis.port}")
    private int port;

    @Value(value = "${spring.redis.password:''}")
    private String password;

//    @Bean(destroyMethod = "shutdown")
//    public RedissonClient redisson() {
//        Config config = new Config();
//        SingleServerConfig singleServerConfig = config.useSingleServer();
//        String address = "redis://" + host + ":" + port;
//        singleServerConfig.setAddress(address);
//        singleServerConfig.setPassword(password);
//        return Redisson.create(config);
//    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> objectObjectRedisTemplate = new RedisTemplate<>();
        // 序列化
        FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
        objectObjectRedisTemplate.setKeySerializer(fastJsonRedisSerializer);
        objectObjectRedisTemplate.setValueSerializer(fastJsonRedisSerializer);
        objectObjectRedisTemplate.setHashKeySerializer(fastJsonRedisSerializer);
        objectObjectRedisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
        objectObjectRedisTemplate.setConnectionFactory(redisConnectionFactory());
        return objectObjectRedisTemplate;
    }

    /**
     * Redis 连接工厂
     */
    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName(host);
        redisStandaloneConfiguration.setPort(port);
        if (StringUtils.isNotBlank(password)) {
            redisStandaloneConfiguration.setPassword(RedisPassword.of(password));
        }
        return new LettuceConnectionFactory(redisStandaloneConfiguration);
    }

}
